package com.ebt.m.customer.util;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.text.TextUtils;

import com.ebt.m.customer.event.OnCropEvent;
import com.ebt.m.customer.view.ListDialog;
import com.ebt.m.utils.ConfigData;
import com.ebt.m.utils.ImageSelectUtil;
import com.ebt.m.utils.UriUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 图片选择->保存->上传类
 * Created by archer.qi on 2016/12/17.
 */
public class ImageProcessor implements ListDialog.onMenuSelectListener {

    private static final int REQUESTCODE_CAMERA = 11;
    private static final int REQUESTCODE_ALBUM = 12;
    private static final int REQUEST_CODE_CROP = 13;

    static final int FLAG = 0;

    // 拍照保存路径
    private static final String CAMERA_OUTPUT_TARGET = ConfigData.DATA_PATH + File.separator + "images" + File.separator;

    private static List<String> listData = new ArrayList<>();

    static {
        listData.add("拍照");
        listData.add("从图库选择");
    }

    private ListDialog listDialog;

    private Activity mContext;

    // 拍照完整路径
    private String mAbsoluteTarget;

    public ImageProcessor(Activity context) {
        mContext = context;
    }

    /**
     * 显示图片选择器
     */
    public void showPicker() {
        if (listDialog == null) {
            listDialog = new ListDialog(mContext);
        }
        listDialog.show();
        listDialog.setData(listData);
        listDialog.setFlag(FLAG);
        listDialog.addOnItemClickListener(this);
    }

    /**
     * onActivityResult时调用
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUESTCODE_CAMERA) {
                // TODO 拍照 - > 裁剪
                doCrop(mAbsoluteTarget);
                return;
            }
            if (requestCode == REQUESTCODE_ALBUM) {
                if (data != null) {
                    // TODO 图库 - > 裁剪
                    doCrop(ImageSelectUtil.getPathFromUri(mContext, data.getData()));
                    return;
                }
                return;
            }
            if (requestCode == REQUEST_CODE_CROP) {
                // TODO 裁剪
                File savedFile = new File(CAMERA_OUTPUT_TARGET + "save.png");
                if (savedFile != null && savedFile.exists()) {
                    savedFile.delete();
                }
                EventBus.getDefault().post(new OnCropEvent(mAbsoluteTarget));
                return;
            }
        }
    }

    private void doCrop(String filePath) {
        Bitmap targetBitmap = BitmapUtil.getSampleBitmap(filePath, 400, 400);
        saveBitmap(targetBitmap, "save.png", CAMERA_OUTPUT_TARGET, 70);
        Uri uri = UriUtils.getUriFromFile(new File(CAMERA_OUTPUT_TARGET + "save.png"));
        ImageSelectUtil.crop(mContext, getTargetFile(), uri, REQUEST_CODE_CROP);
        targetBitmap.recycle();
    }

    /**
     * 保存Bitmap
     */
    public static void saveBitmap(Bitmap bitmap, String fileName, String dir,
                                  int quality) {

        if (bitmap == null || TextUtils.isEmpty(dir)
                || TextUtils.isEmpty(fileName)) {
            throw new NullPointerException(
                    "NullException: bitmap is null or dir, fileName is null!");
        }

        File dirFile = new File(dir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        File file = new File(dir, fileName);
        try {
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, quality, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建一个正常的拍照保存路径
     *
     * @return
     */
    private File getTargetFile() {
        // 每次拍照根据时间戳生成一个唯一的文件名
        String fileName = "camera" + System.currentTimeMillis() + ".png";
        mAbsoluteTarget = CAMERA_OUTPUT_TARGET + fileName;
        File dirFile = new File(CAMERA_OUTPUT_TARGET);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        return new File(mAbsoluteTarget);
    }

    @Override
    public void onMenuSelect(int flag, int position, String content) {
        if (flag == FLAG) {
            if (position == 0) {
                ImageSelectUtil.openCamera(mContext, getTargetFile(), REQUESTCODE_CAMERA);
            } else if (position == 1) {
                ImageSelectUtil.openAlbum(mContext, getTargetFile(), REQUESTCODE_ALBUM);
            }
        }
    }
}
